bool fun(pair<int, int>& p1, pair<int, int>& p2) { return p1.first < p2.first; }
class Solution {
public:
    vector<int> smallestRange(vector<vector<int>>& nums) {
        int n = nums.size(), m = nums[0].size();
        vector<pair<int, int>> vv;
        for (int i = 0; i < n; i++) {
            for (auto& e : nums[i]) {
                vv.push_back({e, i});
            }
        }
        sort(vv.begin(), vv.end(), fun);
        // for (int i = 0; i < vv.size(); i++) {
        //     cout << vv[i].first << ' ' << vv[i].second << ':';
        // }
        int left = 0, right = 0, retleft = 0, retright = 100000000;
        unordered_map<int, int> window;
        int nn = vv.size();
        while (right < nn) {
            window[vv[right].second]++;

            while (window.size() >= n) {
            
                if (vv[right].first - vv[left].first < retright - retleft)
                    retright = vv[right].first, retleft = vv[left].first;
                if (--window[vv[left].second] == 0)
                    window.erase(vv[left].second); 
                left++;
            
            }
            right++;
        }
        return {retleft, retright};
    }
};